#!/usr/bin/env python
# -*- coding: utf-8 -*-

from HTMLParser import HTMLParser
import recipe

class GotovimDomaParser(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    self.title = ""
    self.main_photo = ""
    self.ingredients = []
    self.source = ""
    
    self.ingredient_opened = False
    self.title_opened = False
    self.title_done = False

  def handle_starttag(self, tag, attrs):
    if tag == "img" and (u'class', u'photo') in attrs and self.title_done:
      for attr in attrs:
        if attr[0] == u'src':
          self.main_photo = attr[1].encode('utf-8')
    if tag == "h1" and (u'class', u'rcptitle fn') in attrs:
      self.title_opened = True
    elif tag == "li" and (u'class', u'ingredient') in attrs:
      self.ingredient_opened = True
    elif tag == "a" and self.title_opened:
      for attr in attrs:
        if attr[0] == u'href':
          self.source = attr[1].encode('utf-8')
    else:
      self.ingredient_opened = False

  def handle_endtag(self, tag):
    if self.title_opened:
      self.title_done = True
    self.ingredient_opened = False
    self.title_opened = False

  def handle_data(self, data):
    if self.title_opened:
      self.title = data.encode('utf-8')

    if self.ingredient_opened:
      self.ingredients.append(data.encode('utf-8'))

  def get_parsed_recipe(self):
    r = recipe.Recipe()
    r.title = self.title
    r.ingredients = self.ingredients
    r.main_photo = self.main_photo
    r.source = "http://gotovim-doma.ru" + self.source
    return r